import React from 'react'
import { Upload, message, Button } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import { connect } from 'react-redux'
import { getLuckySheetConf, changeTempOption, saveTemp } from '../../redux/actionCreator/lineLossTempActionCreater'
import LuckyExcel from 'luckyexcel'
import moment from 'moment'

//上传外部文件从excel
function TempUploadFromExcel (props) {
  //将状态和方法解构出来,直接使用
  let { changeTempOption, saveTemp, viewId, insertDate } = props

  const uploadExcel = (file) => {
    LuckyExcel.transformExcelToLucky(file, function (exportJson, luckysheetfile) {

      if (exportJson.sheets === null || exportJson.sheets.length === 0) {
        return message.error("不支持此文件或者文件为空")
      }

      window.luckysheet.destroy()
      //修改此时的模板数据
      changeTempOption(viewId, insertDate, JSON.stringify(exportJson.sheets))
      //上传后将数据保存到后台
      saveTemp(viewId, "上传的模板", exportJson.sheets, moment().format('YYYY-MM-DD HH:mm:ss'))
    })
  }

  const uploadProps = {
    accept: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    name: 'file',
    maxCount: 1,
    showUploadList: false,
    action: "http://localhost:8081/system/lineLossFill/test",
    headers: {
      satoken: localStorage.getItem("satoken"),
    },
    // 限制上传类型
    beforeUpload: file => {
      // 上传前判断是否为xlsx文件，拒绝除此以外的文件
      const isXlsx = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isXlsx) {
        message.error(`${file.name} 不是Xlsx文件`)
      } else {
        //读取到的excel的数据
        //uploadFilesChange(file)
        uploadExcel(file)
      }
      return isXlsx || Upload.LIST_IGNORE
    },
    onChange (file) {
    },
  }


  return (
    <Upload {...uploadProps} className="tempUpload">
      <Button icon={<UploadOutlined />}>上传外部模板覆盖此模板</Button>
    </Upload>
  )
}
// 将state映射到props中
const mapStateToProps = (state) => {
  return {
    luckySheetOption: state.LineLossTempReducer.luckySheetOption,
    viewId: state.LineLossTempReducer.viewId,
    insertDate: state.LineLossTempReducer.insertDate
  }
}

//这是修改redux状态的方法
const mapDispatchToProps = {
  getLuckySheetConf,
  changeTempOption,
  saveTemp
}

export default connect(mapStateToProps, mapDispatchToProps)(TempUploadFromExcel)